package com.ssy.lingxi.platform.template.service.serviceimpl.mobile;

import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.constant.template.PageTemplateTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignRoleIdAndNameVO;
import com.ssy.lingxi.platform.template.service.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.template.service.entity.adorn.AppAdorn;
import com.ssy.lingxi.platform.template.service.entity.adorn.PageTemplate;
import com.ssy.lingxi.platform.template.service.entity.door.MemberChannel;
import com.ssy.lingxi.platform.template.service.model.dto.mobile.MemberChannelMainMobileDTO;
import com.ssy.lingxi.platform.template.service.model.vo.mobile.MemberChannelMainMobileVO;
import com.ssy.lingxi.platform.template.service.model.vo.mobile.MemberChannelUpperMobileVO;
import com.ssy.lingxi.platform.template.service.repository.AppAdornRepository;
import com.ssy.lingxi.platform.template.service.repository.MemberChannelRepository;
import com.ssy.lingxi.platform.template.service.repository.PageTemplateRepository;
import com.ssy.lingxi.platform.template.service.service.mobile.MemberChannelMobileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @menu mobile - 会员渠道 - 业务实现层
 * @author fhj
 * @version 2.0.0
 * @date 2020/12/30
 */
@Slf4j
@Service
public class MemberChannelMobileServiceImpl implements MemberChannelMobileService {

    @Resource
    private MemberChannelRepository memberChannelRepository;
    @Resource
    private PageTemplateRepository pageTemplateRepository;
    @Resource
    private AppAdornRepository appAdornRepository;
    @Resource
    private MemberInnerControllerFeign memberInnerControllerFeign;

    @Override
    @ApiOperation(value = "会员渠道主页")
    public Wrapper<MemberChannelMainMobileVO> memberChannelMain(MemberChannelMainMobileDTO dto) {
        //根据会员ID获取会员渠道
        MemberChannel memberChannel = memberChannelRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        if(memberChannel == null) {
            return Wrapper.fail(ResponseCode.PT_NOT_FOUND_MEMBER_SHOP);
        }

        //拷贝
        MemberChannelMainMobileVO memberChannelMainMobileVO = new MemberChannelMainMobileVO();
        BeanUtils.copyProperties(memberChannel, memberChannelMainMobileVO);

        //封装正在使用的渠道或渠道自有模板装修内容
        List<PageTemplate> pageTemplateList = pageTemplateRepository.findByTypeAndStatusAndShelfAndShopId(
                PageTemplateTypeEnum.CHANNEL.getCode(),
                CommonBooleanEnum.YES.getCode(),
                CommonBooleanEnum.YES.getCode(),
                dto.getShopId()
        );
        if(CollectionUtil.isNotEmpty(pageTemplateList)) {
            pageTemplateList = pageTemplateList.stream().filter(a ->
                    CollectionUtil.isNotEmpty(a.getUseChannelTemplate()) &&
                            a.getUseChannelTemplate().stream().anyMatch(b ->
                                    b.getMemberId().equals(memberChannel.getMemberId()) && b.getRoleId().equals(memberChannel.getRoleId())
                            )
            ).collect(Collectors.toList());

            //渠道模板和渠道自有模板
            if(CollectionUtil.isNotEmpty(pageTemplateList)) {
                if (pageTemplateList.size() > 1) {
                    log.error("正在使用的渠道模板出现多个【检查原因】");
                }
                PageTemplate pageTemplate = pageTemplateList.get(0);

                AppAdorn appAdorn = appAdornRepository.findByTemplateIdAndMemberIdAndRoleId(
                        pageTemplate.getId(),
                        memberChannel.getMemberId(),
                        memberChannel.getRoleId()
                );
                memberChannelMainMobileVO.setTemplateId(pageTemplate.getId());
                if(appAdorn != null) {
                    memberChannelMainMobileVO.setAdornContent(appAdorn.getAdornContent());
                }
            }
        }

        return Wrapper.success(memberChannelMainMobileVO);
    }

    @Override
    @ApiOperation(value = "根据邀请码获取渠道商")
    public Wrapper<MemberChannel> findByInviteCode(String inviteCode, UserLoginCacheDTO user) {
        if(StringUtils.isBlank(inviteCode)) {
            return Wrapper.fail(ResponseCode.PT_INVITATION_CODE_CANNOT_BE_EMPTY);
        }
        return Wrapper.success(memberChannelRepository.findByInviteCode(inviteCode));
    }

    @Override
    @ApiOperation(value = "获取上级渠道商")
    public Wrapper<List<MemberChannelUpperMobileVO>> findUpperChannel(UserLoginCacheDTO user) {
        //调用会员服务 -> 根据会员id和角色id，查询上级“渠道会员”列表
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(user.getMemberId());
        memberFeignVO.setRoleId(user.getMemberRoleId());
        Wrapper<List<MemberFeignRoleIdAndNameVO>> wrapper = memberInnerControllerFeign.listUpperChannelMembers(memberFeignVO);
        if(wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("调用会员服务失败：{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_MERCHANT_MEMBER_ERROR);
        }
        if(CollectionUtil.isEmpty(wrapper.getData())) {
            return Wrapper.success(new ArrayList<>());
        }

        //先根据会员ID获取渠道会员, 再根据会员ID和角色ID来筛选渠道商
        List<MemberChannel> memberChannelList = memberChannelRepository.findAllByMemberIdIn(
                wrapper.getData().stream().map(MemberFeignRoleIdAndNameVO::getMemberId).collect(Collectors.toList())
        );
        memberChannelList = memberChannelList.stream().filter(a ->
                wrapper.getData().stream().anyMatch(b ->
                        b.getMemberId().equals(a.getMemberId()) && b.getRoleId().equals(a.getRoleId())
                )
        ).collect(Collectors.toList());

        //拼装返回
        return Wrapper.success(
                memberChannelList.stream().map(a -> {
                    MemberChannelUpperMobileVO vo = new MemberChannelUpperMobileVO();
                    BeanUtils.copyProperties(a, vo);
                    return vo;
                }).collect(Collectors.toList())
        );
    }
}
